<template>
	<div>
		<van-nav-bar
		  title="新增收货地址"
			left-text="返回"
			 @click-left="handleLeftClick"
		/>
		<van-address-edit
		  :area-list="areaList"
		  show-postal
			:address-info="formData"
		  show-delete
		  show-set-default
		  show-search-result
		  :area-columns-placeholder="['请选择', '请选择', '请选择']"
			@change-area="handleAreaChange"
		  @save="onSave"
		  @delete="onDelete"
		  @change-detail="onChangeDetail"
		/>
	</div>
</template>

<script>
	import {areaList} from '@/data/areaList.js'
	import {updateAddress,findAddressById,deleteAddressById} from '@/api/address-api.js'
	export default{
		data(){
			return {
				areaList:areaList,
				formData:{}
			}
		},
		async created(){
			let id = this.$route.query.id
			await this.findAddressById(id)
		},
		methods:{
			async findAddressById(id){
				let res = await findAddressById(id)
				if(res.data.code == 200){
					let formData = res.data.data
					this.formData = {
						...formData,
						provinceCode:formData.provinceId,
						cityCode:formData.cityId+"",
						areaCode:formData.areaId+"",
						tel:formData.phone,
						postalCode:formData.postCode+"",
						isDefault:!!formData.isDefault,
						addressDetail:formData.address
					}
				}
			},
			handleLeftClick(){
				this.$router.history.go(-1)
			},
			async onSave(formData){
				this.formData = {
					...this.formData,
					...formData,
					phone:formData.tel,
					postCode:formData.postalCode,
					isDefault:formData.isDefault?1:0,
					address:formData.addressDetail
				}
				let res = await updateAddress(this.formData)
				if(res.data.code ==200){
					this.$router.history.go(-1)
				}
			},
			async onDelete(){
				let res = await deleteAddressById(this.formData.id)
				if(res.data.code == 200){
					this.$router.history.go(-1)
				}
			},
			onChangeDetail(res){
				console.log(res)
			},
			handleAreaChange(res){
				if(res.length>0){
					this.formData.provinceId = res[0].code
					this.formData.province = res[0].name
					this.formData.cityId = res[1].code
					this.formData.city = res[1].name
					this.formData.areaId = res[2].code
					this.formData.area = res[2].name
				}
			}
		}
	}
</script>

<style>
</style>
